% UniversalDecoder
% Max Fagin (07/31/11)
% Additional code by Patrick Yukman (10/19/11)
%
% Program decodes and plots Magentometer, Accelerometer and GPS data file
% collected from the droid phone, SquidBee, GreenCube or Altair Payload
 
clear all
 
% ------------------ User Inputs (specify before run) ---------------------
 
% Specify files from which data are to be read
    FileGPS  =  'ALTAIR Recovery DNT.txt';  % GPS (i.e. Position)
    FileAcc  =  'nov7solarpaneltemptest.txt';        % Accelerometer
    FileMag  =  'nov7solarpaneltemptest.txt';        % Magnetometer
    FileDat  =  'nov7solarpaneltemptest.txt';        % Other data from payload (Voltage, counts, etc)
    FileTop  =  'AltairTopoData.txt';       % Local Topo Data (Optional)
 
% Specify device type from which file data originates
% 1 = Droide Phone     (DR)
% 2 = SquidBee         (SQ)
% 3 = GreenCube        (GR)
% 4 = Altair Payload   (AL)
 
    SourceGPS  = 1;            
    SourceAcc  = 2;            
    SourceMag  = 2;
    SourceDat  = 2;
    
    
% Specify data to be plotted
% 

 
% -------------------------------------------------------------------------
 
% ---------------------- Data Format Specifications -----------------------
 
% Time resolution of data in data points per second for
tsDP = 1;       % Droid
tsSQ = 10;       % SquidBee
tsGC = 1;       % GreenCube
tsOS = 1;       % Altair

% Standard # of digits being printed from DR or SQ (if used)
StdDigits = 4;

AMNDC = 18;
DNDC = 6;

AMDigits = AMNDC+(StdDigits*3);
DDigits = DNDC+ StdDigits;
 
% -------------------------- Decoder -------------------------------------- 
 
% Initiate Data vectors
 
Gt  = [];   % GPS
Lat = [];
Lon = [];
Alt = [];

At  = [];    % Accelerometer
Ax  = [];
Ay  = [];
Az  = [];
 
Mt  = [];    % Magnetometer
Mx  = [];
My  = [];
Mz  = [];
 
Dt  = [];    % Data Channels
D0  = [];
D1  = [];
D2  = [];
D3  = [];
 
%Import data
 
% GPS
%ActiveFile = fopen(FileGPS,'r');                  % Set raw data file to user specified source
%ActiveData = fread(ActiveFile, inf, '*char')';    % Import all data from active file into a single text string
% 
%if SourceGPS == 1           % If from Droid
%elseif SourceGPS == 2       % If from SquidBe
%elseif SourceGPS == 3       % If from GreenCube
%elseif SourceGPS == 4       % If from Altair
%       
%    for n=1:length(ActiveData)          % Read all data
%        
%        if ActiveData(n) == '$' && ActiveData(n+1) == 'G' && ActiveData(n+2) == 'P' && ActiveData(n+3) == 'G' % If GPS string identified
%            
%            Gt =  [Gt ,str2double(ActiveData(n+7:n+16))];                                           % Extract the gps time stamp and append it to the vector of gps time values
%            Lat = [Lat,str2double(ActiveData(n+18:n+19))+str2double(ActiveData(n+20:n+26))/60];     % Extract the lattitude "
%            Lon = [Lon,-(str2double(ActiveData(n+30:n+32))+str2double(ActiveData(n+33:n+39))/60)];  % Extract the longitude "
%            Alt = [Alt,str2double(ActiveData(n+52:n+57))];                                          % Extract the altitude  "
%        end   
%    end
    
 % UNCOMMENT TO WRITE DATA TO GOOGLEEARTH FILE
    %LastFix = {Gt(length(Gt)), Lon(length(Lon)), Lat(length(Lat)), Alt(length(Alt))};
    %ActiveFile = fopen('KMLconverter.txt','w');   
    %for n=1:length(Gt)-1
        %fprintf(ActiveFile, '%4.10g, %4.10g, %4.10g \n', Lon(n),Lat(n),Alt(n));
    %end
    
        
%else
%    'Unknown Input';
%end
 
% ACCELEROMETER
ActiveFile = fopen(FileAcc,'r');                  % Set raw data file to user specified source
ActiveData = fread(ActiveFile, inf, '*char')';    % Import all data from active file into a single text string
 
if SourceAcc == 1                   % If from Droid    
 
elseif SourceAcc == 2               % If from SqiudBee
    Valid = 0;                          % Index to indicate whether or not current data string is valid to be read
    DataAxis = 0;                       % Index to identify current axis (1 = X, 2 = Y, 3 = Z)
    for n=1:length(ActiveData)          % Read all data
        
        if ActiveData(n) == 'A'      % Only read data when the previous line charcter was 'A', not when it is 'M' or 'D'
            Valid = 1;
        elseif ActiveData(n) == 'M' || ActiveData(n) == 'D'
            Valid = 0;
        end
        
        if ActiveData(n) == 'X'      % Identify which axis is currentally being read
            DataAxis = 1;
        elseif ActiveData(n) == 'Y'
            DataAxis = 2;
        elseif ActiveData(n) == 'Z'
            DataAxis = 3;
        end
        
        if ActiveData(n) == ':' && Valid == 1;      % Begin logging data if current data being read is valid
            if DataAxis == 1;
                Ax = [Ax,str2double(ActiveData(n+2:n+(3+StdDigits)))]; 
            elseif DataAxis == 2;
                Ay = [Ay,str2double(ActiveData(n+2:n+(3+StdDigits)))];
            elseif DataAxis == 3;
                Az = [Az,str2double(ActiveData(n+2:n+(3+StdDigits)))];
            end
        end 
    end
    At = linspace(0,length(Ax)/tsSQ,length(Ax));   % Add the next point to the time index of accelerometer data
    
    
elseif SourceAcc == 3               % If from GreenCube
elseif SourceAcc == 4               % If from Altair
else
    'Unknown Input';
end
 
    
% MAGNETOMETER
ActiveFile = fopen(FileMag,'r');                  % Set raw data file to user specified source
ActiveData = fread(ActiveFile, inf, '*char')';    % Import all data from active file into a single text string
 
if SourceMag == 1                   % If from Droid    
elseif SourceMag == 2               % If from SqiudBee
    Valid = 0;                          % Index to indicate whether or not current data string is valid to be read
    DataAxis = 0;                       % Index to identify current axis (1 = X, 2 = Y, 3 = Z)
    for n=1:length(ActiveData)          % Read all data
        
        if ActiveData(n) == 'M'      % Only read data when the previous line charcter was 'M', not when it is 'A' or 'D'
            Valid = 1;
        elseif ActiveData(n) == 'A' || ActiveData(n) == 'D'
            Valid = 0;
        end
        
        if ActiveData(n) == 'X'      % Identify which axis is currentally being read
            DataAxis = 1;
        elseif ActiveData(n) == 'Y'
            DataAxis = 2;
        elseif ActiveData(n) == 'Z'
            DataAxis = 3;
        end
        
        if ActiveData(n) == ':' && Valid == 1;      % Begin logging data if current data being read is valid
            if DataAxis == 1;
                Mx = [Mx,str2double(ActiveData(n+2:n+(3+StdDigits)))]; 
            elseif DataAxis == 2;
                My = [My,str2double(ActiveData(n+2:n+(3+StdDigits)))];
            elseif DataAxis == 3;
                Mz = [Mz,str2double(ActiveData(n+2:n+(3+StdDigits)))];
            end
        end
    end
    Mt = linspace(0,length(Mx)/tsSQ,length(Mx));   % Add the next point to the time index of accelerometer data
    
elseif SourceMag == 3               % If from GreenCube
elseif SourceMag == 4               % If from Altair
else
    'Unknown Input';
end
 
 
%DATA
ActiveFile = fopen(FileDat,'r');                  % Set raw data file to user specified source
ActiveData = fread(ActiveFile, inf, '*char')';    % Import all data from active file into a single text string
 
if SourceDat == 1                   % If from Droid    
elseif SourceDat == 2               % If from SqiudBee
    Valid = 0;                          % Index to indicate whether or not current data string is valid to be read
    DataAxis = 0;                       % Index to identify current axis (0 = V1, 1 = V2, 1 = T, 2 = L)
    for n=1:length(ActiveData)          % Read all data
        
        if ActiveData(n) == 'D';
            DataAxis = str2double(ActiveData(n+1));
     
            if DataAxis == 0;
                D0 = [D0,str2double(ActiveData(n+3:n+(4+StdDigits)))];
            elseif DataAxis == 1;
                D1 = [D1,str2double(ActiveData(n+3:n+(4+StdDigits)))];
            elseif DataAxis == 2;
                D2 = [D2,str2double(ActiveData(n+3:n+(4+StdDigits)))];
            elseif DataAxis == 3;
                D3 = [D3,str2double(ActiveData(n+3:n+(4+StdDigits)))];
            end
        end 
    end
   
    
    Dt = linspace(0,length(D1)/tsSQ,length(D1));      % Add the next point to the time index of accelerometer data
    
    
elseif SourceDat == 3               % If from GreenCube
elseif SourceDat == 4               % If from OS4000T Compass
    
   
    
     for n=1:length(ActiveData)          % Read all data
        
        if ActiveData(n) == '$' && ActiveData(n+1) == 'G' && ActiveData(n+2) == 'P' && ActiveData(n+3) == 'G' % If GPS string identified
            Dt =  [Dt ,str2double(ActiveData(n+7:n+16))];
            Dt =  [Dt ,str2double(ActiveData(n+7:n+16))+.1]; 
            Dt =  [Dt ,str2double(ActiveData(n+7:n+16))+.2]; 
        end   
        
        if ActiveData(n) == '$' && ActiveData(n+1) == 'C'% If attitude string identified
 
            D0 = [D0 ,str2double(ActiveData(n+2:n+4))];
        end
        
     end 


%Dt = Dt(2:length(D0)+1);
    
else
    'Unknown Input';
end
 
   

% -------------------------- Plot Results --------------------------------
 
% % Plot Results

%Ugly hack (REMOVE FOR ANY FILE NOT SOLARTEST.TXT)
%Ax=[Ax,0,0];
%Ay=[Ay,0,0];
%Az=[Az,0,0,0];
%Mx=[Mx,0,0,0];
%My=[My,0];
%Mz=[Mz,0,0];
%D1=[D1,0,0,0,0,0,0];
%D2=[D2,0,0];
%D3=[D3,0,0,0];
%Mt=[Mt,0,0,0];
%At=[At,0,0];
%Dt=[Dt,0,0,0,0,0,0];

% subplot(1,3,1)
% plot(Lon(2:445),Alt(2:445));
% xlabel('Lon');
% ylabel('Alt');
% axis([-71.548 -71.540 0 7000]);
% 
% subplot(1,3,2)
% plot(Lat(2:445),Alt(2:445));
% xlabel('Lat');
% ylabel('Alt');
% axis([43.945 43.97 0 7000]);
% 
% subplot(1,3,3)
% plot(Lon(2:445),Lat(2:445));
% xlabel('Lon');
% ylabel('Lat');
% axis square

% plot3(Lon(2:length(Lon)),Lat(2:length(Lat)),Alt(2:length(Alt)))
% grid on
% axis([-71.557 -71.527 43.94 43.97 700 7000])
% axis vis3d

%hist(Vz,min(Vz):.1:max(Vz))
%axis([-71.548 -71.537 0 200])
%axis([-20 -4 0 50])

%{
subplot(3,1,1);
plot(At,Ax,'b',At,Ay,'r',At,Az,'g');
xlabel('Time (sec)')
ylabel('Acceleration (# Counts)');
legend('Ax','Ay','Az');

subplot(3,1,2);
plot(Mt,Mx,'m',Mt,My,'k',Mt,Mz,'c');
xlabel('Time (sec)');
ylabel('Magnetometer (# Counts)');
legend('Mx','My','Mz');
%}
 
% plot(At,Ax,'b',At,Ay,'r',At,Az,'y',Mt,Mx,'m',Mt,My,'k',Mt,Mz,'g');
% xlabel('Time (?)');
% ylabel('# Counts');
% legend('Ax','Ay','Az','Mx','My','Mz');
% axis([0,1.1*length(At),-1300,900]);

%subplot(3,1,3)
%plot(Dt,D0,'k',Dt,D1,'b',Dt,D2,'m',Dt,D3,'r');
%xlabel('Time (sec)');
%ylabel('Data');
%legend('D0','D1','D2','D3'); % change these labels when the final sensor configuration is chosen

%scatter(D0./D3,D1,'.');
scatter(Dt,D1,'.');
%D0-solar panel
%D1-thermistor
%D3-photometer
%xlabel('~Voltage');
%ylabel('~Phot');